﻿using System;
using System.IO;
using System.Web.Mvc;
using SharePointEditor.BusinessDefinitions.Serialization;

namespace SharePointEditor.Web.Helpers
{
    /// <summary>
    /// Validates a model against data annotation
    /// </summary>
    [AttributeUsage(AttributeTargets.All, Inherited = true, AllowMultiple = true)]
    public class JsonFilter : ActionFilterAttribute
    {
        /// <summary>
        /// Gets or sets the param.
        /// </summary>
        /// <value>The param.</value>
        public string Param { get; set; }
        /// <summary>
        /// Gets or sets the type of the json data.
        /// </summary>
        /// <value>The type of the json data.</value>
        public Type JsonDataType { get; set; }

        /// <summary>
        /// Called before the action method executes.
        /// </summary>
        /// <param name="filterContext">The filter context.</param>
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (filterContext.HttpContext.Request.ContentType.Contains("application/json"))
            {
                string inputContent;
                using (var sr = new StreamReader(filterContext.HttpContext.Request.InputStream))
                {
                    inputContent = sr.ReadToEnd();
                }
                
                var result = JSONSerializer.DeSerialize(inputContent, JsonDataType);
                filterContext.ActionParameters[Param] = result;
            }
        }
    }
}